package com.yima.baseproj.module.app.Controller;

import cn.hutool.core.date.DateTime;
import com.yima.baseproj.module.app.Controller.model.QueryModel;
import com.yima.baseproj.security.annotation.SecurityIgnoreUrl;
import com.yima.baseproj.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "门禁设备")
@RequestMapping("/api/app/equipment")
@RestController
@Component
public class equipmentController {
    //appID
    private static final String APPID = "52A5A9157E3942AE830EFC1D6AB2A86F";
    //key
    private static final String KEY = "1B55A7A4FF794BECB85773C13A0B07A7";
    //Secret;
    private static final String APP_SECRET = "CE815C7A01C74647A051F8BE8FFF09C8";

    //    @Scheduled(cron = "0 0 0/5 * * *")  //每五个小时
//    @Scheduled(cron = "0 0 0/10 * * *") //每10个小时
//    @Scheduled(cron = "0 * * * * ?") //每分钟
//    @Scheduled(cron = "0 0 */1 * * ?") //每1小时
    @PostConstruct
    @Scheduled(cron = "0 0 */1 * * ?")
    public static void init() throws Exception {
        authentication();
    }

    @ApiOperation("鉴权接口")
    @SecurityIgnoreUrl(isNeedResultVo = false)
    @GetMapping(value = "/authentication")
    public static R authentication() throws Exception {
        String timestamp = String.valueOf(System.currentTimeMillis());
        //鉴权
        String sign = MD5.getMD5(KEY + timestamp + APP_SECRET);
        String s = HttpClientUtil.sendGetRequest(APPID, KEY, timestamp, sign);
        org.json.JSONObject json = new JSONObject(s);
        String data = json.getString("data");
        CacheUtil.Jedis("authenticationToken", data);
        String token = CacheUtil.getValue("authenticationToken");

        // 判断是否鉴权成功
        if (token != null && !"null".equals(token)) {
            System.out.println("鉴权成功，authenticationToken为：" + token);
            return R.success("鉴权成功", token);
        } else {
            System.out.println("鉴权失败：authenticationToken为：" + (token != null ? token : "null"));
//            init();
            return R.error("鉴权失败");
        }
    }
}
